package com.woniu.service.impl;

import com.woniu.mapper.PowerDao;
import com.woniu.pojo.Power;
import com.woniu.pojo.PowerExample;
import com.woniu.service.PowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class powerServiceImpl implements PowerService {
    @Autowired
    PowerDao powerDao;

    @Override
    public void add(Power power) {
        powerDao.insert(power);
    }

    @Override
    public List<Power> findAll() {
        List<Power> tree=new ArrayList<>();
        List<Power> powers = powerDao.selectByExample(null);
        Map<Integer,Power> map=new HashMap<>();
            for(Power p:powers ){
                map.put(p.getPowerId(),p);
                p.setOpen(true);
            }
        for(Power p:powers){
            if(p.getParentId()==null){
                tree.add(p);
            }else {
                map.get(p.getParentId()).getChildren().add(p);
            }
        }
        return tree;
    }

    @Override
    public Integer addOready(Power power) {
        powerDao.insert(power);
        PowerExample example=new PowerExample();
        example.createCriteria().andPowerNmaeEqualTo("请编辑");
        List<Power> powers = powerDao.selectByExample(example);
        if(powers!=null&&powers.size()>0){
            Integer powerId = powers.get(0).getPowerId();
            return powerId;
        }
        return null;
    }
}
